package redistool;

import swing.CommonPanel;
import swing.CommonTree;
import swing.NewConnectionFrame;
import utils.PropertiesUtil;
import utils.RedisUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: GaleBlade
 * @date:
 */
public class RedisTool extends JFrame {

    private JFrame main = new JFrame("RedisTool ver1.0");
    private Container contentPane = main.getContentPane();
    private JPanel treePanel;
    public JLabel topLabel = new JLabel("已选:");
    private static CommonPanel exhibitPanel = new CommonPanel();
    private static CommonPanel editPanel = new CommonPanel();
    private JButton searchBtn = new JButton("查询");
    private JButton copyBtn = new JButton("复制");
    private JButton saveBtn = new JButton("保存");
    public String key = "";
    public int db = 0;
    public Color bgColor = new Color(67,67,67);
    public Font font = new Font("Menu.font", Font.PLAIN, 15);
    public RedisUtils redisUtils;
    private NewConnectionFrame newConnectionFrame = new NewConnectionFrame(this);
    private Map<String,Integer> heightMap = new HashMap<>();
    private Map<String,Integer> widthMap = new HashMap<>();
    private List<String> treeNameList = new ArrayList<>();
    private List<CommonTree> treeList = new ArrayList<>();

    public RedisTool() throws IOException {
        //初始化菜单栏
        initMenu();
        //初始化主面板和相关组件
        initComponents();
        //初始化树
        initTrees();
        //初始化按钮
        initBtns();
    }

    /**
     * 获取redis连接
     */
    public void getRedisConnect(String host, String port, String auth){
        redisUtils = new RedisUtils(host,port,auth);
    }

    /**
     * 初始化菜单栏
     */
    public void initMenu(){
        //创建并添加菜单栏
        JMenuBar menuBar = new JMenuBar();
        main.setJMenuBar(menuBar);
        //创建并添加各菜单，注意：菜单的快捷键是同时按下Alt键和字母键，方法setMnemonic('F')是设置快捷键为Alt +Ｆ
        JMenu menuFile = new JMenu("连接(F)");
        menuFile.setMnemonic('F');
        menuBar.add(menuFile);
        //添加“连接”菜单的各菜单项
        JMenuItem itemNew = new JMenuItem("新建连接");
        menuFile.add(itemNew);
        itemNew.addActionListener(e -> {
            //显示新建连接弹窗
            newConnectionFrame.setVisible(true);
        });
    }

    /**
     * 初始化树
     */
    public void initTrees(){
        //读取配置文件
        PropertiesUtil info = new PropertiesUtil("INFO.properties");
        //获取配置文件中的所有key
        treeNameList = info.getAllKeys();
        //根据key的数量和名称初始化树
        for (int i=0;i<treeNameList.size();i++){
            String name = treeNameList.get(i);
            addTree(name, info.get(name), i);
            //顺带初始化宽高的map
            widthMap.put(name, 0);
            heightMap.put(name, 25);
        }
    }

    /**
     * 添加树
     */
    public void addTree(String name, String url, int i){
        //根据name初始化树根节点
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(name);
        top.setUserObject(name);
        //根据url获取redis连接信息
        String[] cache = url.split(";");
        String host = cache[0];
        String port = cache[1];
        String auth = "";
        if (cache.length > 2){
            auth = cache[2];
        }
        //声明一个CommonTree实例
        CommonTree tree = new CommonTree(i, top, name, host, port, auth, this);
        //把tree添加到list
        treeList.add(i, tree);
        //把tree添加到面板
        treePanel.add(tree);
        //刷新面板
        refreshFrame();
    }

    /**
     * 删除树
     */
    public void removeTree(String name){
        int no = 0;
        CommonTree tree = new CommonTree();
        for (CommonTree treeCache : treeList){
            if (treeCache.name.equals(name)){
                no = treeList.indexOf(treeCache);
                tree = treeCache;
            }
        }
        //刷新面板
        refreshPanel(no, "", 0, 25, 0);
        treeList.remove(tree);
        //刷新CommonTree类中的排序
        treePanel.remove(tree);
        for (int i=0;i<treeList.size();i++){
            treeList.get(i).i = i;
        }
        refreshFrame();
    }

    /**
     * 初始化主面板和相关组件
     */
    public void initComponents() throws IOException {
        //设置左侧树面板
        treePanel = new JPanel();
        treePanel.setLayout(null);
        treePanel.setBounds(10,10,300,740);
        treePanel.setBackground(Color.GRAY);
        treePanel.setPreferredSize(new Dimension(280, 720));
        //给树面板添加滚动条
        JScrollPane treeScroll = new JScrollPane(treePanel);
        treeScroll.setBounds(10,10,300,740);
        treeScroll.getViewport().setBackground(Color.GRAY);
        treeScroll.getVerticalScrollBar().setUnitIncrement(20);
        //设置右侧查询区和输入区组件
        topLabel.setBounds(320,5,450,30);
        exhibitPanel.setEditable(false);
        topLabel.setFont(font);
        topLabel.setForeground(Color.WHITE);
        exhibitPanel.setBounds(320,40,450,300);
        editPanel.setBounds(320,400,450,300);
        //把所有组件添加到面板
        contentPane.setLayout(null);
        contentPane.add(treeScroll);
        contentPane.add(topLabel);
        contentPane.add(exhibitPanel);
        contentPane.add(searchBtn);
        contentPane.add(copyBtn);
        contentPane.add(saveBtn);
        contentPane.add(editPanel);
        contentPane.setBackground(bgColor);
        //设置程序启动时窗口出现的位置
        int screenWidth= java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
        int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
        main.setLocation((screenWidth-800)/2, (screenHeight-820)/2);
        main.setSize(800, 820);
        main.setVisible(true);
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置图标
        main.setIconImage(ImageIO.read(new File("resources/logo.png")));
    }

    /**
     * 初始化按钮
     */
    public void initBtns(){
        searchBtn.setBounds(405,355,70,30);
        copyBtn.setBounds(625,355,70,30);
        saveBtn.setBounds(515,715,70,30);
        searchBtn.setFont(font);
        copyBtn.setFont(font);
        saveBtn.setFont(font);
        //按钮点击处理 lambda表达式
        searchBtn.addActionListener((e) -> {
            redisUtils.select(db);
            String field = exhibitPanel.getField();
            String value = redisUtils.getValue(key,field);
            exhibitPanel.setValueArea(value);
        });
        //按钮点击处理 lambda表达式
        copyBtn.addActionListener((e) -> {
            editPanel.setKeyArea(exhibitPanel.getField());
            editPanel.setValueArea(exhibitPanel.getValue());
        });
        //按钮点击处理 lambda表达式
        saveBtn.addActionListener((e) -> {
            redisUtils.setValue(key,editPanel.getField(),editPanel.getValue());
        });
    }

    /**
     * 刷新窗口
     */
    public void refreshFrame(){
        main.invalidate();
        main.validate();
        main.repaint();
    }

    /**
     * 刷新树面板
     */
    public void refreshPanel(int no, String name, int width, int heightOld, int heightNew){
        for (int i=no+1;i<treeList.size();i++) {
            treeList.get(i).refreshBounds(heightNew - heightOld);
        }
        if (name.equals("")){
            widthMap.remove(name);
            heightMap.remove(name);
        }else {
            widthMap.put(name, width);
            heightMap.put(name, heightNew);
        }
        int widthFinal = 0;
        int heightFinal = 0;
        for (String s : treeNameList) {
            if (widthMap.get(s) > widthFinal){
                widthFinal = widthMap.get(s);
            }
            heightFinal += heightMap.get(s);
        }
        treePanel.setPreferredSize(new Dimension(widthFinal, heightFinal));
    }

}
